/*
	FileName : JT_C_ADC_RMS.c
	Description :
		Caculate RMS of wave.
	
	Created on 2018.01.08 by WFL.

	Revision History:

*/


/* Includes ------------------------------------------------------------------*/


#include "math.h"
#include "JT_C_ADC_RMS.h"

//---------------------

JTC_ADC_RMS JTC_rms_12;
JTC_ADC_RMS JTC_rms_34;

//---------------------

uint8_t JTC_ADC_RMS_init(JTC_ADC_RMS *rms,uint16_t number,uint16_t valmax)
{
	if(valmax > JTC_ADC_RMS_VAL_MAX)
		return 1;
	
	if(number > JTC_ADC_RMS_NUMBER_MAX)
		return 1;
	
	rms->RMS_Number = number;
	rms->RMS_Count = 0;
	rms->RMS_Sum = 0;
	rms->RMS_QuaSum = 0;
	
	rms->RMS_Result = 0;
	rms->RMS_Average = 0;
	
	return 0;
}

void JTC_ADC_RMS_findbiggest(JTC_ADC_RMS *rms)
{
	uint8_t i;
	
	for(i=0; i<JTC_RMS_CACHE_NUMBER-1; i++)
	{
		rms->RMS_cache[i] = rms->RMS_cache[i+1];
	}
	rms->RMS_cache[JTC_RMS_CACHE_NUMBER-1] = rms->RMS_Result;
	
	rms->RMS_biggest = 0;
	for(i=0; i<JTC_RMS_CACHE_NUMBER; i++)
	{
		if(rms->RMS_biggest < rms->RMS_cache[i])
			rms->RMS_biggest = rms->RMS_cache[i];
	}
	return;
}

uint8_t JTC_ADC_RMS_handle(JTC_ADC_RMS *rms,uint16_t val)
{
	uint32_t temp;
	
	rms->RMS_Sum += val;
	rms->RMS_QuaSum += (val * val);
	rms->RMS_Count ++;
	
	if(rms->RMS_Count < rms->RMS_Number)
		return 0;
	
	rms->RMS_Average = rms->RMS_Sum / rms->RMS_Count;
	
	temp = rms->RMS_QuaSum / rms->RMS_Count;
	temp = temp - ((uint32_t)rms->RMS_Average  * rms->RMS_Average);
	
	rms->RMS_Result = sqrt(temp);
	
	rms->RMS_Count = 0;
	rms->RMS_Sum = 0;
	rms->RMS_QuaSum = 0;
	
	JTC_ADC_RMS_findbiggest(rms);
	
	return 1;
}

//-----------------------------------------------------------------------
///EOF
